<?php
	if (empty($_POST['nit']) || empty($_POST['clave'])) exit;
	
	include 'config.php';
	
	$query = "SELECT u.id, u.nit, u.nombre, uAux.nit AS nit_aliado FROM usuarios u LEFT OUTER JOIN usuarios uAux ON u.aliado = uAux.id WHERE u.nit = :nit AND u.clave = SHA1(PASSWORD(:clave))";
	$valores = array(':nit' =>$_POST['nit'], ':clave' => $_POST['clave']);
	
	try {
		$dbh = new PDO('mysql:host=' . $host . ';dbname=' . $db, $user, $password, $options);
		$stmt = $dbh -> prepare($query);
		$stmt -> execute($valores);

		$numFilas = $stmt -> rowCount();
		if ($numFilas == 1){
			$row = $stmt -> fetch();
			
			session_start();
			$_SESSION['id'] = $row['id'];
			$_SESSION['nit'] = $row['nit'];
			$_SESSION['nombre'] = $row['nombre'];
			$_SESSION['nit_aliado'] = $row['nit_aliado'];
			$forwardPage = "index.php";
			$dbh = null;
			
			$ftp_server = "repositorio.ipsuniversitaria.com.co";
			$ftp_user_name = "ghipsftp";
			$ftp_user_pass = "ftpghips";
			
			if ($_SESSION['nit_aliado'] == NULL)
			{
				$local_file = 'Excel/BD_EmpleadosIPS.xls';
				$server_file = 'Recurso Humano/BASE_DE_DATOS_PERSONAL_VINCULADO_PRESTADORES_APRENDICES_E_INDUCCIONES.xls';
			}
			else
			{
				$local_file = 'Excel/BD_EmpleadosAliados.xls';
				$server_file = 'Recurso Humano/Copia de BASE DE DATOS UNIFICADA 2.xlsx';
			}
			
			// set up basic connection
			$conn_id = ftp_connect($ftp_server);
			// echo "Conn: " . $conn_id; 
			// login with username and password
			$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
			if (filemtime($local_file) < time() - (60 * 5)){
				ftp_get($conn_id, $local_file, $server_file, FTP_BINARY);
			}
			//echo print_r(ftp_nlist($conn_id, "."));
			/* echo "login: " . $login_result;
			// try to download $server_file and save to $local_file
			if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
				echo "Successfully written to $local_file\n";
			} else {
				echo "There was a problem\n";
			}  */

			// close the connection
			ftp_close($conn_id);
			
			header("Location: " . $forwardPage);
			exit();
		}
		else{
			session_start();
			
			$forwardPage = "login.php";
			$dbh = null;
			header("Location: " . $forwardPage . "?intento=1");
			exit();
		}
		$dbh = null;
	} catch (PDOException $e) {
		print "Error!: " . $e->getMessage() . "<br/>";
		die();
	}
?>